package com.nf.health.app.chatservice.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.PathUtil;
import com.nf.health.app.AppModel;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.http.Act;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.models.GroupInfo;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDiscountCard;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDoctorAdvice;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDoctorCard;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDoctorQuestion;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowDrugAlert;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowHealthAlert;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowImageMessage;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowOnlyMessage;
import com.nf.health.app.widget.custom_chatrow.EaseChatRowSystemCard;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 群聊天界面
 */
public class ChatActivityGroup extends BaseActivity {

    private static final String TAG = ChatActivityGroup.class.getSimpleName();
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;
    private static final int ITEM_PICTURE = 1;
    private static final int ITEM_TAKE_PICTURE = 2;
    private static final int ITEM_EVALUATION = 5;
    public static final String EXTRA_DOCTOR_TYPE = "extra_doctor_type";


    //消息类型
    private static final int MESSAGE_TYPE_RECV_HEALTH_ALERT = 1;
    private static final int MESSAGE_TYPE_RECV_DRUG_ALERT = 2;
    private static final int MESSAGE_TYPE_RECV_DOCTOR_QUESTION = 3;
    private static final int MESSAGE_TYPE_RECV_IMAGE_MESSAGE = 4;
    private static final int MESSAGE_TYPE_RECV_ONLY_MESSAGE = 5;
    private static final int MESSAGE_TYPE_RECV_DOCTOR_ADVICE = 6;
    private static final int MESSAGE_TYPE_RECV_DOCTOR_CARD = 7;
    private static final int MESSAGE_TYPE_RECV_DISCOUNT_CARD = 8;
    private static final int MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM = 9;

    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.titlebar_right_tv)
    TextView titlebarRightTv;
    @Bind(R.id.message_list)
    EaseChatMessageList messageList;
    @Bind(R.id.voice_recorder)
    EaseVoiceRecorderView voiceRecorderView;
    @Bind(R.id.input_menu)
    EaseChatInputMenu inputMenu;
    public ChatActivityGroup activityInstance;

    private String toChatUsername;
    protected int chatType;
    protected String doctorType;
    protected SwipeRefreshLayout swipeRefreshLayout;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected int[] itemStrings = {R.string.chat_picture, R.string.chat_camera, R.string.chat_evaluation};
    protected int[] itemdrawables = {R.drawable.ic_chat_picture,
            R.drawable.ic_chat_camera,
            R.drawable.ic_chat_evaluation};
    protected int[] itemIds = {ITEM_PICTURE, ITEM_TAKE_PICTURE, ITEM_EVALUATION};

    protected MyItemClickListener extendMenuItemClickListener;
    private ListView listView;
    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected EMConversation conversation;

    private boolean isMessageListInited;
    protected File cameraFile;
    private UserInfo userInfo;
    private String is_forFit = new String(); //是否被群主禁言了

    private BroadcastReceiver receiver;
    int state;

    @Override
    protected void onCreate(Bundle arg0) {
        //保存聊天界面的对象,以便cmd监听时调用,
        LogUtil.i(TAG, "oncreate");
        super.onCreate(arg0);
        userInfo = PreferenceHelper.getUser();
        activityInstance = this;
        //聊天人或群id
        toChatUsername = getIntent().getExtras().getString(EaseConstant.EXTRA_USER_ID);
        chatType = EaseConstant.CHATTYPE_GROUP;
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_chat_group);
        ButterKnife.bind(this);
        titlebarRightTv.setOnClickListener(this);

        is_forFit = DbManager.getInstance().getOneGroupState(toChatUsername).getIsForbit();
        initView();
        initListener();
        registReceiver();
    }


    private void initView() {
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            messageList.setShowUserNick(true);
            ViewUtil.setText(this, R.id.titlebar_right_tv, "设置");
            titlebarRightTv.setVisibility(View.VISIBLE);
        }
        listView = messageList.getListView();
        extendMenuItemClickListener = new MyItemClickListener();

        inputMenu.init(null);
        inputMenu.setChatInputMenuListener(new EaseChatInputMenu.ChatInputMenuListener() {

            @Override
            public void onSendMessage(String content) {
                // 发送文本消息
                sendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderView.EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        // 发送语音消息
                        sendVoiceMessage(voiceFilePath, voiceTimeLength);
                    }
                });
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                //发送大表情(动态表情)
                sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
            }
        });

        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(com.hyphenate.easeui.R.color.holo_blue_bright, com.hyphenate.easeui.R.color.holo_green_light,
                com.hyphenate.easeui.R.color.holo_orange_light, com.hyphenate.easeui.R.color.holo_red_light);

        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        //其他的一些view
        setUpView();
        //扩展栏view
        registerExtendMenuItem(2);
    }

    private void setUpView() {
        //设置标题
        titlebarTitleTv.setText(toChatUsername);
        //处理群聊或聊天室
        if (!TextUtils.isEmpty(is_forFit)) {
            if (is_forFit.equals("y")) {//是群聊，进项禁言
                setMyGroupForbit(true);
            } else {
                setMyGroupForbit(false);
            }
        }
        //设置群标题
        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
        titlebarTitleTv.setText(group != null ? group.getGroupName() : toChatUsername);
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }
        //下拉刷新
        setRefreshLayoutListener();
    }

    private void initListener() {
        titlebarRightView.setOnClickListener(this);
    }


    protected void onConversationInit() {
        // 获取当前conversation对象

        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();
        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }
    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatType, new CustomChatRowProvider());
        //设置list item里的控件的点击事件
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });

        isMessageListInited = true;
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                            List<EMMessage> messages;
                            try {
                                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                                    messages = conversation.loadMoreMsgFromDB(messageList.getItem(0).getMsgId(),
                                            pagesize);
                                } else {
                                    messages = conversation.loadMoreMsgFromDB(messageList.getItem(0).getMsgId(),
                                            pagesize);
                                }
                            } catch (Exception e1) {
                                swipeRefreshLayout.setRefreshing(false);
                                return;
                            }
                            if (messages.size() > 0) {
                                messageList.refreshSeekTo(messages.size() - 1);
                                if (messages.size() != pagesize) {
                                    haveMoreData = false;
                                }
                            } else {
                                haveMoreData = false;
                            }

                            isloading = false;

                        } else {
                            Toast.makeText(ChatActivityGroup.this, getResources().getString(com.hyphenate.easeui.R.string.no_more_messages),
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {//点击头像跳到医生主页
                if (toChatUsername.equals(username)) {//自己的头像不能点击,这里还不能判断群里的医生,有待改进
                    EMMessage msg = conversation.getLastMessage();
                    String type = "";
                    try {
                        type = msg.getStringAttribute(Constants.EMContact.EF_DoctorType).split("_")[0];
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                    if ("40".equals(type)) {
                        //健康助手
                        Bundle bundle = new Bundle();
                        bundle.putString(DocDetailActivity.DOCTORID, username);
                        ActivityUtils.showActivity(ChatActivityGroup.this, DocDetailActivity.class, bundle);
                        return;
                    } else if ("30".equals(type)) {
                        //健康银行
                        Bundle bundle = new Bundle();
                        bundle.putString(DocDetailActivity.DOCTORID, username);
                        ActivityUtils.showActivity(ChatActivityGroup.this, DocDetailActivity.class, bundle);
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString(DocDetailActivity.DOCTORID, username);
                    ActivityUtils.showActivity(ChatActivityGroup.this, DocDetailActivity.class, bundle);
                }
            }

            @Override
            public void onResendClick(final EMMessage message) {
                new EaseAlertDialog(activityInstance, com.hyphenate.easeui.R.string.resend, com.hyphenate.easeui.R.string.confirm_resend, null, new EaseAlertDialog.AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        resendMessage(message);
                    }
                }, true).show();
            }

            @Override
            public void onBubbleLongClick(EMMessage message) {
                //TODO
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
                //TODO
                return false;
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 设置扩展栏
     */
    private void registerExtendMenuItem(int count) {
        for (int i = 0; i < 2; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
        inputMenu.getExtendMenu().setNumColumns(2);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }
    }

    //发送消息方法
    //==========================================================================
    protected void sendTextMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        sendMessage(message);
    }

    protected void sendBigExpressionMessage(String name, String identityCode) {
        EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, name, identityCode);
        sendMessage(message);
    }

    protected void sendVoiceMessage(String filePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        sendMessage(message);
    }

    protected void sendImageMessage(String imagePath) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        sendMessage(message);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        sendMessage(message);
    }


    protected void sendMessage(EMMessage message) {
//        if(chatFragmentListener != null){
//            //设置扩展属性
//            chatFragmentListener.onSetMessageAttributes(message);
//        }
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }
        String name = userInfo.getRname();
        if(TextUtils.isEmpty(name)){
            name = userInfo.getNick();
        }
        if (userInfo != null && !TextUtils.isEmpty(name)) {
            message.setAttribute(Constants.EMContact.EF_USERNAME, name);
        } else {
            message.setAttribute(Constants.EMContact.EF_USERNAME, toChatUsername);
        }
        if (userInfo != null && !TextUtils.isEmpty(userInfo.getHimg())) {
            message.setAttribute(Constants.EMContact.EF_USERICON, userInfo.getHimg());
        } else {
            message.setAttribute(Constants.EMContact.EF_USERICON, "");
        }
        //发送EF_DoctorType附加字段
        if (doctorType != null) {
            message.setAttribute(Constants.EMContact.EF_DoctorType, doctorType);
        } else {
            //默认是普通患者发送
            message.setAttribute(Constants.EMContact.EF_DoctorType, "10_");
        }
        //发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
        //刷新ui
        if (isMessageListInited) {
            messageList.refreshSelectLast();
        }
    }


    public void resendMessage(EMMessage message) {
        message.setStatus(EMMessage.Status.CREATE);
        EMClient.getInstance().chatManager().sendMessage(message);
        messageList.refresh();
    }


    /**
     * 扩展菜单栏item点击事件
     */
    class MyItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            switch (itemId) {
                case ITEM_TAKE_PICTURE: // 拍照
                    selectPicFromCamera();
                    break;
                case ITEM_PICTURE:
                    selectPicFromLocal(); // 图库选择图片
                    break;
                case ITEM_EVALUATION: // 评价
                    inputMenu.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 照相获取图片
     */
    protected void selectPicFromCamera() {
        if (!EaseCommonUtils.isExitsSdcard()) {
            Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 从图库获取图片
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            }
        }
    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = activityInstance.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(activityInstance, com.hyphenate.easeui.R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendImageMessage(file.getAbsolutePath());
        }

    }

    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {

            for (EMMessage message : messages) {
                String username = null;
                // 群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    // 单聊消息
                    username = message.getFrom();
                }

                // 如果是当前会话的消息，刷新聊天页面
                if (username.equals(toChatUsername)) {
                    messageList.refreshSelectLast();
                    // 声音和震动提示有新消息
                    EaseUI.getInstance().getNotifier().viberateAndPlayTone(message);
                } else {
                    // 如果消息不是和当前聊天ID的消息
                    EaseUI.getInstance().getNotifier().onNewMsg(message);
                }
                //通知
                try {
                    EaseUser user = new EaseUser(message.getFrom());
                    String name = message.getStringAttribute(Constants.EMContact.EF_USERNAME);
                    String himg = message.getStringAttribute(Constants.EMContact.EF_USERICON);
                    user.setNick(name);
                    user.setAvatar(himg);
                    AppModel.getInstatnce().saveContact(user);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            if (messages.size() > 0) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) messages.get(0).getBody();
                String action = cmdMsgBody.action();
                EMMessage model = messages.get(0);
                if (Constants.THE_SPECIAL_SIGN_FORBIT_USER_ACTION.equals(action)) {//禁言的cmd消息
                    try {
                        String is_forFit = model.getStringAttribute(Constants.THE_SPECIAL_SIGN_FORBIT_USER_TTALK);
                        String groupId = model.getStringAttribute(Constants.THE_SPECIAL_SIGN_FORBIT_GROUP_ID);
                        GroupInfo groupInfo = new GroupInfo();
                        groupInfo.setUsername(groupId);
                        groupInfo.setIsForbit(is_forFit);
                        DbManager.getInstance().addOneGroupState(groupInfo);
                        if (is_forFit.equals("y")) {//是群聊，进项禁言
                            setMyGroupForbit(true);
                        } else {
                            setMyGroupForbit(false);
                        }
                        onCreate(null);

                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageList.refresh();
        EaseUI.getInstance().pushActivity(activityInstance);
        // register the event listener when enter the foreground
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);

        // 把此activity 从foreground activity 列表里移除
        EaseUI.getInstance().popActivity(activityInstance);
    }


    /**
     * 响应点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_tv://群设置
                Bundle chatBundle = new Bundle();
                chatBundle.putString(EaseConstant.EXTRA_USER_ID, toChatUsername);
                //ActivityUtil.showActivity(ChatActivity.this, GroupDetailsActivity.class, chatBundle);
                ActivityUtils.showActivityForResult(ChatActivityGroup.this, GroupChatSettingActivity.class, chatBundle, Constants.CODE_EXIT);
                break;
            default:
                break;
        }
    }


    /**
     * 网络请求处理
     *
     * @param actionName
     * @param object
     */
    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.GET_SERVICE_STATUS_FLG.equals(actionName)) {
            String data = (String) object;
        }
    }

    /**
     * 是否禁止群成员发表言论
     *
     * @param isClick 为true是群组禁言，为false的话，取消禁言，正常发表
     */
    private void setMyGroupForbit(boolean isClick) {
        try {
            inputMenu.setEnabled(!isClick);
            inputMenu.setClickable(!isClick);
            messageList.setClickable(!isClick);
            voiceRecorderView.setEnabled(!isClick);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isClick) {
            inputMenu.setVisibility(View.GONE);
        } else {
            inputMenu.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    //注册 广播和接收
    private void registReceiver() {
        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (Constants.CHAT_CLOSE.equals(action)) {
                    finish();
                } else if (Constants.THE_SPECIAL_SIGN_FORBIT_USER_ACTION.equals(action)) {

                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.CHAT_CLOSE);
        registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        LogUtil.i(TAG, "ondestory");
        super.onDestroy();
        if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
        }
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            return 8;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            try {
                if (message.getType() == EMMessage.Type.TXT) {
                    String msgType = message.getStringAttribute("EF_MessageType");
                    if (msgType.equals(Constants.MESSAGE_TYPE_RECV_HEALTH_ALERT)) {
                        return MESSAGE_TYPE_RECV_HEALTH_ALERT;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DRUG_ALERT)) {
                        return MESSAGE_TYPE_RECV_DRUG_ALERT;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_QUESTION)) {
                        return MESSAGE_TYPE_RECV_DOCTOR_QUESTION;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_IMAGE_MESSAGE)) {
                        return MESSAGE_TYPE_RECV_IMAGE_MESSAGE;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_ONLY_MESSAGE)) {
                        return MESSAGE_TYPE_RECV_ONLY_MESSAGE;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_ADVICE)) {
                        return MESSAGE_TYPE_RECV_DOCTOR_ADVICE;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_CARD)) {
                        return MESSAGE_TYPE_RECV_DOCTOR_CARD;

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_CARD)) {
                        return MESSAGE_TYPE_RECV_DISCOUNT_CARD;

                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM)) {
                        return MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM;

                    }
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            try {
                if (message.getType() == EMMessage.Type.TXT) {
                    String msgType = message.getStringAttribute("EF_MessageType");
                    if (msgType.equals(Constants.MESSAGE_TYPE_RECV_HEALTH_ALERT)) {//健康预警
                        return new EaseChatRowHealthAlert(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DRUG_ALERT)) {//用药提醒
                        return new EaseChatRowDrugAlert(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_QUESTION)) {//医生问卷
                        return new EaseChatRowDoctorQuestion(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_IMAGE_MESSAGE)) {//图文消息
                        return new EaseChatRowImageMessage(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_ONLY_MESSAGE)) {//纯文消息
                        return new EaseChatRowOnlyMessage(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_ADVICE)) {//医嘱计划
                        return new EaseChatRowDoctorAdvice(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DOCTOR_CARD)) {//医生名片
                        return new EaseChatRowDoctorCard(ChatActivityGroup.this, message, position, adapter,state);

                    } else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_CARD)) {//医生优惠码
                        return new EaseChatRowDiscountCard(ChatActivityGroup.this, message, position, adapter,state);
                    }else if (msgType.equals(Constants.MESSAGE_TYPE_RECV_DISCOUNT_SYSTEM)) {//医生优惠码
                        return new EaseChatRowSystemCard(ChatActivityGroup.this, message, position, adapter,state);
                    }
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
